package com.yumingjiang.common.template;

import com.alibaba.fastjson2.JSONObject;
import com.yumingjiang.common.model.Result;
import com.yumingjiang.common.util.ResultUtil;
import com.yumingjiang.component.cache.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @description:
 * @author: John
 * @version: ServiceOpRedisTemplate.java, v1.0 2024年12月31日 20:02
 */
@Slf4j
@Component
public class ServiceOpRedisTemplate {

    @Autowired
    private RedisService redisService;

    public Result process(String key, CommonCallback callback) {

        try {
            Result result = redisService.get(key);
            if (Objects.nonNull(result)) {
                log.info("缓存查得数据，result:" + JSONObject.toJSONString(result));
                return result;
            }
            result = callback.doBiz();

            if (result.isSuccess() && result.getData() != null) {
                log.info("更新缓存数据，key:" + key + " value:" + JSONObject.toJSONString(result));
                redisService.put(key, result);
            }
            return result;
        } catch (Exception e) {
            log.error("服务调用异常", e);
        }
        return ResultUtil.buildError();
    }
}